<?php


namespace App\Web\Model;


use EchoPHP\Facades\Db;
use Ramsey\Uuid\Uuid;

class User {

    //账号注册来源
    const SOURCE_REGISTER = '01';
    const SOURCE_LDAP = '02';
    //用户觉得
    const ROLE_USER = 1;
    const ROLE_ADMIN = 2;
    const ROLE_SUPER = 3;

    /**
     * 根据邮箱获取用户信息
     * @param $email
     * @param null $field
     * @return array
     */
    public function getUserByEmail($email, $field = null) {
        $field = $field ?? 'userid,email';
        $sql = 'SELECT ' . $field . ' FROM user WHERE email=?';
        $var = [$email];

        return Db::connect()->selectOne($sql, $var);
    }

    /**
     * 添加用户
     * @param $email
     * @param $password
     * @param $nickname
     * @param $source
     * @return int|mixed    用户id
     */
    public function addUser($email, $password, $nickname, $source) {
        try {
            $salt = Uuid::uuid1()->toString();
        } catch (\Exception $e) {
            return 0;
        }
        $password = $this->encryptPwd($password, $salt);
        $source = $source == self::SOURCE_LDAP ? self::SOURCE_LDAP : self::SOURCE_REGISTER;
        try {
            $adminEmail = config('app.admin_email', '');
        } catch (\Exception $e) {
            $adminEmail = '';
        }
        if ($email == $adminEmail) {
            $role = self::ROLE_SUPER;
        } else {
            $role = self::ROLE_USER;
        }
        $sql = 'INSERT INTO user(email, password, salt, nickname, role,islock, source) VALUES (?,?,?,?,?,?,?)';
        $var = [$email, $password, $salt, $nickname, $role, 0, $source];

        $result = Db::connect()->insert($sql, $var);
        if (!$result) {
            return 0;
        }
        return Db::connect()->getLastInsertId();
    }

    /**
     * 生成密钥
     * @param $password
     * @param $salt
     * @return string
     */
    public function encryptPwd($password, $salt) {
        return md5(substr(crypt(md5($password), substr($salt, 3, 2)), 1, 5) . strrev($password) . $salt);
    }


}